﻿using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class InjectionIServiceCollectionExtensions
    {
        public static IServiceCollection RegisterInjectionServices<T>(this IServiceCollection services)
        {
            var serviceTypes = typeof(T).Assembly.GetTypes()
                .Where(a => a.IsClass)
                .Where(a => a.GetCustomAttribute<InjectionAttribute>() != null)//扫描注解
                .Where(a => !a.IsAbstract);
            foreach (var item in serviceTypes)
            {
                var injection = item.GetCustomAttribute<InjectionAttribute>();
                if (injection!.ServiceType == null)
                {
                    services.Add(new ServiceDescriptor(item, item, injection.Lifetime));
                }
                else
                {
                    services.Add(new ServiceDescriptor(injection!.ServiceType, item, injection.Lifetime));
                }
            }
            return services;
        }
    }
}
